#include <string.h>
#include "station.h"

#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1

static const char *TAG = "WIFI 客户端";
SemaphoreHandle_t sync_WIFI_Connect;
uint8_t reConnect = 0;


void WIFI_ConnectTask(void)
{
    int result;
    wifi_config_t wifi_config;
    
    sync_WIFI_Connect = xSemaphoreCreateBinary();
    for(;;)
    {
        ESP_LOGE(TAG,"等待触发 WIFI连接任务...");
        xSemaphoreTake(sync_WIFI_Connect, portMAX_DELAY);
        ESP_LOGE(TAG,"已触发 WIFI连接任务...");

        esp_wifi_get_config(WIFI_IF_STA, &wifi_config);
        strcpy((char *)(wifi_config.sta.ssid), g_wifi_ssid);
        strcpy((char *)(wifi_config.sta.password), g_wifi_password);
        ESP_LOGE(TAG, "配置WIFI SSID %s Password is %s", wifi_config.sta.ssid, wifi_config.sta.password);
        ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
        
        if(wireless_state.station_state != disconnect)
        {
            ESP_LOGE(TAG,"断开已连接的WIFI");
            esp_wifi_disconnect();
            wireless_state.station_state = disconnect;
        }
        result = esp_wifi_connect();
        if(result != ESP_OK)
        {
            ESP_LOGE(TAG,"WIFI连接失败,原因: %d", result);
        }
        else if(reConnect < 0xff) reConnect++;
        if(reConnect >= 3) gatt_wifi_state(0);
        ESP_LOGE(TAG,"WIFI连接第 %d 次失败", reConnect);
    }
}

void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
    {
        ESP_LOGE(TAG, "WIFI STA启动后,执行该事件");
        wifi_config_t wifi_config = {
            .sta = {
                .ssid = "null",
                .password = "null",
                .scan_method = WIFI_FAST_SCAN,
                .sort_method = WIFI_CONNECT_AP_BY_SIGNAL,
                .threshold.rssi = -127,
                .threshold.authmode = WIFI_AUTH_WPA2_PSK,
                .pmf_cfg = {
                    .capable = true,
                    .required = false
                },
            },
        };
        ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
        ESP_LOGE(TAG, "配置WIFI SSID %s Password is %s", wifi_config.sta.ssid, wifi_config.sta.password);
    }
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
    {
        wifi_event_sta_disconnected_t* data;

        data = (wifi_event_sta_disconnected_t*)event_data;
        ESP_LOGE(TAG,"连接失败 原因(%d), 重连路由器",data->reason);
        // vTaskDelay(pdMS_TO_TICKS(400));
        WIFI_ReConnect_Trigger();
    }
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED)
    {
        // (wifi_event_sta_connected_t*)event_data
        ESP_LOGE(TAG, "WIFI 已连接...成功");
        ESP_LOGE(TAG, "已连接到路由器: SSID: %s, Password: %s", g_wifi_ssid, g_wifi_password);
        gatt_wifi_state(1);
        wireless_state.nvs_save_inform = get_inform; //保存wifi信息
        wireless_state.station_state = connected;
        reConnect = 0;
    }
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
    {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGE(TAG, "获取路由器的 ip:" IPSTR, IP2STR(&event->ip_info.ip));

        AWS_ConnectTrigger();
        // OTA_Trigger();
    }
    else
    {
        ESP_LOGE(TAG, "未处理事件: %s, %d", event_base, event_id);
        // gatt_wifi_state(0);
    }
}

esp_err_t wifi_sta_init(void)
{
    ESP_LOGE(TAG, "初始化...");

    ESP_ERROR_CHECK(esp_netif_init());
    // ESP_ERROR_CHECK(esp_event_loop_create_default());
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    //WIFI_PS_MIN_MODEM是WiFi省电的默认模式。当WiFi和蓝牙都运行时，WiFI调制解调器必须关闭，因此我们需要WIFI_PS_MIN_MODEM。随着WiFi调制解调器的关闭，OTA下载时间增加
    esp_wifi_set_ps(WIFI_PS_MIN_MODEM);
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, NULL));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, NULL));
    // Initialize default station as network interface instance (esp-netif)
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta(); //能触发IP事件
    assert(sta_netif);
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_LOGE(TAG, "WIFI 创建STA控制块并启动STA");
    vTaskDelay(pdMS_TO_TICKS(2000));

    ESP_ERROR_CHECK(esp_wifi_start());
    
    xTaskCreate(&WIFI_ConnectTask, "WIFI_ConnTask", 1024 * 8, NULL, 11, NULL);

    return ESP_OK;
}

//断网重连触发
void WIFI_ReConnect_Trigger(void)
{
    xSemaphoreGive(sync_WIFI_Connect); 
}
//WIFI配网触发
void WIFI_Connect_Trigger(void)
{
    reConnect = 0;
    //触发 WIFI连接任务
    xSemaphoreGive(sync_WIFI_Connect);
}

static void disconnect_ap_station() //断开AP
{
    ESP_LOGE(TAG, "close ap mode");                      //关闭AP模式
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));   //设置wifi模式 关闭AP
    vTaskDelay(10000 / portTICK_RATE_MS);                //延迟 断开AP
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA)); //设置wifi模式 开启AP
    ESP_LOGE(TAG, "restart ap mode");                    //重启AP模式
    vTaskDelete(NULL);
}

//wifi信号强度
// wifi_ap_record_t ap_info;
// ESP_ERROR_CHECK(esp_wifi_sta_get_ap_info(&ap_info));
// ESP_LOGE(TAG, "RSSI \t\t%d", ap_info.rssi);

void MemSize(char* txt)
{
    ESP_LOGW(txt, "芯片可用内存: %d",esp_get_free_heap_size());
    // ESP_LOGE("芯片", "从未使用过的最小内存: %d",esp_get_minimum_free_heap_size());
}